import React, { Component, Fragment } from "react";
// antd
import { Modal, Table, Button, Col, Pagination, Form, Input, message, Tag } from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../utils/request';

// import { UnControlled as CodeMirror } from 'react-codemirror2';
import { Controlled as CodeMirror } from 'react-codemirror2';


// 引入 yaml 依赖（因为我需要yaml语言 大家可以自行引入javascript java c++等 参考官网）
import 'codemirror/mode/yaml/yaml';
// import "codemirror/mode/javascript/javascript";


// 引入codemirror核心css,js文件（经试验css必须有，js文件还没发现它的用处）
import 'codemirror/lib/codemirror.css';
import 'codemirror/lib/codemirror.js'


// 引入 ambiance 主题
import 'codemirror/theme/neat.css';
import 'codemirror/theme/darcula.css';
import 'codemirror/theme/juejin.css';
import 'codemirror/theme/lucario.css';
import 'codemirror/theme/neo.css';
import 'codemirror/theme/nord.css';
import 'codemirror/theme/pastel-on-dark.css';
// import { truncate } from "fs-extra";

// // 引入 yamljs
// const getYAMLJS = require('yamljs');

function ListItem(props) {
    return <div style={{ marginTop: "8px"}}><Tag color="success">{props.value}</Tag></div>
}

class CloudManage extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "任务名称", dataIndex: "name", key: "name"},
                {title: "描述", dataIndex: "describe", key: "describe"},
                {title: "TASK", dataIndex: "task_list", key: "task_list",
                    render: (text, rowData) => {
                        const listItems = rowData.task_list.map((item) => 
                                <ListItem key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }
                },
                {title: "操作", dataIndex: "operation", key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditAnsibleBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                    <Action.Button onClick={() => this.onDeleteAnsibleBtn(rowData)}>删除</Action.Button>
                                </Action>
                            </div>

                        )
                    }           
                }
            ],
            loading: false,
            visible_add: false,     // 添加
            visible_edit: false,    // 编辑
            visible_delete: false,  // 删除
            visible_edit_id: '',
            visible_edit_name: '',
            visable_edit_code: '',
            ansible_id: '',
            ansible_name: '',
            ansible_yaml: '',
            search_ansible_name: '',
        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefMsg = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        console.log('didmount thisL: ', this)
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'name__contains': this.state.search_ansible_name,
        }

        // 获取分组列表
        http.get('/ansible/task', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_ansible_name: data.name ? data.name : null,
        })
        this.loadData()
    }

    /** 添加按钮 */
    onAddAnsibleBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 添加取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false,
            ansible_yaml: '',
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加提交 */
    onFinishAdd = (data) => {
        const requestData = {
            name: data.name,
            yaml: this.state.ansible_yaml,
            describe: data.describe,
        }
        http.post('/ansible/task', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 编辑按钮 */
    onEditAnsibleBtn = (data) => {
        http.get('/ansible/task').then(response=> {
            this.formRefEdit.current.setFieldsValue({
                id: data.rowData.id,
                name: data.rowData.name,
                // yaml: data.rowData.yaml,
                describe: data.rowData.describe,
            })
        })
        
        this.setState({
            visible_edit: true,
            ansible_yaml: data.rowData.yaml,
        })
    }

    /** 编辑取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false,
            ansible_yaml: '',
        })
        this.formRefEdit.current.resetFields();
    }

    /** 编辑提交 */
    onFinishEdit = (data) => {
        const requestData = {
            name: data.name,
            describe: data.describe,
            yaml: this.state.ansible_yaml,
        }
        http.put('/ansible/task/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false
            })
            this.formRefEdit.current.resetFields();
            this.loadData()
        }).catch()
    }

    /** 删除提交 */
    handleAnsibleDelete = () => {
        http.delete('/ansible/task/' + this.state.ansible_id).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_delete: false,
            })
            this.loadData()
        }).catch()    
    }

    /** 删除按钮 */
    onDeleteAnsibleBtn = (data) => {
        this.setState({
            ansible_id: data.id,
            ansible_name: data.name,
            visible_delete: true
        })
    }

    onBeforeChange = (editor, data, value) => {
        console.log(value)
        this.setState({
            ansible_yaml: value
        })
    }

    render(){
        const { loading, dataSource, columns, page, total, visible_add, visible_edit, visible_delete, ansible_name, ansible_yaml } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>       

                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="任务名称" name="name">
                        <Input placeholder="请输入任务名称"  />
                    </Form.Item>
                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                <div style={myStyle1}><Button type="primary" onClick={this.onAddAnsibleBtn}>添加Ansible任务</Button></div>
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="添加任务"
                    visible={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1000}
                    keyboard={false}
                    maskClosable={false}
                >

                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                    >
                        <Form.Item label="任务名称" name="name" rules={[{ required: true}]}>
                            <Input style={{ width: '719px' }}></Input>
                        </Form.Item>

                        <Form.Item label="任务描述" name="describe" rules={[{ required: true}]}>
                            <Input style={{ width: '719px' }}></Input>
                        </Form.Item>

                        <span style={{color: 'red'}}>* </span>Playbooks：
                        <CodeMirror
                            value={ansible_yaml}
                            options={{
                                lineNumbers: true, // 显示行号
                                theme: 'darcula', // 设置主题
                                // readOnly: true, // 只读(有用)
                                mode: { // 实现代码高亮
                                    name: 'text/x-yaml',
                                    // name: "javascript", // 没错，需要先引入 javascript
                                    // json: true
                                },
                            }}
                            style={{ "height": "800px" }}
                            onBeforeChange={this.onBeforeChange}
                        />
                        <div style={myStyle}></div>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="编辑Ansible任务"
                    visible={visible_edit}
                    onCancel={this.onFinishEditCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1000}
                    keyboard={false}
                    maskClosable={false}
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                    >
                        <Form.Item label="ID" name="id" hidden>
                            <Input></Input>
                        </Form.Item>
                        <Form.Item label="任务名称" name="name" rules={[{ required: true}]}>
                            <Input style={{ width: '719px' }}></Input>
                        </Form.Item>

                        <Form.Item label="任务描述" name="describe" rules={[{ required: true}]}>
                            <Input style={{ width: '719px' }}></Input>
                        </Form.Item>

                        <span style={{color: 'red'}}>* </span>Playbooks:
                        <CodeMirror
                            value={ansible_yaml}
                            options={{
                                lineNumbers: true, // 显示行号
                                theme: 'darcula', // 设置主题
                                // readOnly: true, // 只读(有用)
                                mode: { // 实现代码高亮
                                    name: 'text/x-yaml',
                                    // name: "javascript", // 没错，需要先引入 javascript
                                    // json: true
                                },
                            }}
                            style={{ "height": "800px" }}
                            onBeforeChange={this.onBeforeChange}
                        />
                        <div style={myStyle}></div>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除任务"
                    visible={visible_delete}
                    onOk={this.handleAnsibleDelete}
                    onCancel={() => {this.setState({visible_delete: false, ansible_id: ''})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>确定删除任务<span style={{color: 'red'}}> {ansible_name}</span>? 删除后将无法恢复</p>
                </Modal>
            </Fragment>
        )
    }
}
export default CloudManage;